package com.SmartHelmet.Web;

import com.SmartHelmet.model.helmet;
import com.SmartHelmet.model.wearHelmet;
import com.SmartHelmet.model.worker;
import com.SmartHelmet.service.HelmetService;
import com.SmartHelmet.service.WearHelmetService;
import com.SmartHelmet.service.WorkerService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.annotation.Resource;
import java.util.List;

/**
 * Created by Administrator on 2016/12/8.
 */
@Controller
@RequestMapping("/Wear")
public class WearController {
    @Resource
    WearHelmetService wearHelmetService;

    @Resource
    HelmetService helmetService;

    @Resource
    WorkerService workerService;


    @RequestMapping(value = "list",method = RequestMethod.GET)
    public String List(Model model)
    {
        List<wearHelmet> result=wearHelmetService.getAllList();
        model.addAttribute("wears",result);
        return "Wear/list";
    }

    @RequestMapping(value = "new",method = RequestMethod.GET)
    public String new_wear()
    {
        return "Wear/new";
    }

    /**
     * 保存配戴关系
     * @param code
     * @param workerId
     * @return
     */
    @RequestMapping(value = "new",method = RequestMethod.POST)
    public String save_new_wear(Model model,String code,String workerId)
    {
        helmet helmetModel=helmetService.getByCode(code);
        worker workerModel=workerService.getWorker(Integer.valueOf(workerId));
        if(helmetModel==null)
        {
            model.addAttribute("err","头盔序列号没找到");
            return "Wear/new";
        }

        if(workerModel==null)
        {
            model.addAttribute("err","工位没找到");
            return "Wear/new";
        }

        if(helmetModel!=null && workerModel!=null)
        {
            boolean wearResult=wearHelmetService.wear(Integer.valueOf(workerId),helmetModel.getId());
            if(!wearResult)
            {
                model.addAttribute("err","头盔已绑定给其它工位请先删除之前的配戴关系");
                return "Wear/new";
            }
        }
        return "redirect:/Wear/list";
    }

    @RequestMapping(value = "del/{id}",method = RequestMethod.GET)
    public String del(@PathVariable int id)
    {
        wearHelmetService.deleteWear(id);
        return "redirect:/Wear/list";
    }

    @RequestMapping(value = "modify/{id}",method = RequestMethod.GET)
    public String modify(@PathVariable int id,Model model)
    {
        model.addAttribute("wear",wearHelmetService.getId(id));
        return "Wear/modify";
    }
}
